package com.example.guavaSrudy.basicPreConditions;

import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;

import static com.google.common.base.Preconditions.*;

public class GuavaBasicUse {

    public static void main(String[] args) {
//        useGuava();
        GuavaBasicUse guavaBasicUse = new GuavaBasicUse();
        PreconditionExample preconditionExample = guavaBasicUse.new PreconditionExample(null);
        preconditionExample.updateCurrentIndexValue(6,50);
        preconditionExample.doOperation();
    }
    static String someObj  = null;
//    来看看自定义的前置条件
    public static void origin() {

        if(someObj == null) {
            throw new IllegalArgumentException(" someObj must not be null");
        }
    }
// 使用guara来操作,代码就简洁了
    public static void useGuava() {
        checkNotNull(someObj,"someObj must not be null");

    }

    public class PreconditionExample {
        private String label;
        private int[] values = new int[5];
        private int currentIndex;

        public PreconditionExample(String label) {
            //returns value of object if not null
            this.label = checkNotNull(label, "Label can''t be null");
        }
        public void updateCurrentIndexValue(int index, int valueToSet) {
            //Check index valid first
            this.currentIndex = checkElementIndex(index, values.length, "Index out of bounds for values");
            //Validate valueToSet
            checkArgument(valueToSet <= 100,"Value can't be more than 100");
            values[this.currentIndex] = valueToSet;
        }
        public void doOperation(){
            checkState(validateObjectState(),"Can't perform operation");
        }

        private boolean validateObjectState(){
            return this.label.equalsIgnoreCase("open") && values[this.currentIndex]==10;
        }
    }
}
